package libra.serviceB;

import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import com.alibaba.nacos.api.exception.NacosException;

import libra.ReqRecord;
import libra.SwProp;
import libra.SwService;

@RestController
public class ServiceB_Controller {
	@Value("${server.port}")
	String port;
	
	@Autowired
	SwService service;
	
	@Autowired
	RestTemplate restTemplate;
	
	@RequestMapping("testReqB")
	public Object testReq(){
		return Map.of("code",0,"port",port);
	}
	
	// 获取服务实例
	@RequestMapping("call")
	public Object call(HttpServletRequest req, HttpServletResponse resp) throws Throwable {
		ReqRecord reqRecord = new ReqRecord();
		reqRecord.setLocalService(SwProp.SwServiceB+"_"+port);
		reqRecord.setRecordTime(new Date());
		ReqRecord postForObject = restTemplate.postForObject("http://"+ SwProp.SwServiceB +"/callback", reqRecord, ReqRecord.class);
		service.save(postForObject);
		return postForObject;
	}
	
	@RequestMapping("callback")
	public Object callback( @RequestBody ReqRecord record, HttpServletRequest req, HttpServletResponse resp) throws NacosException {
		ReqRecord reqRecord = new ReqRecord();
		reqRecord.setLocalService(SwProp.SwServiceB+"_"+port);
		reqRecord.setRecordTime(new Date());
		record.setCall(reqRecord);
		return record;
	}
}
